package main

import (
	"HelloWorld/internal/sorter"
	"bufio"
	"flag"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var (
	infile    *string = flag.String("i", "input.txt", "File contains values for sorting")
	outfile   *string = flag.String("o", "output.txt", "File to receive sorted values")
	algorithm *string = flag.String("a", "qsort", "Sorting algorithm")
)

func readValues(infile string) (values []int, err error) {
	file, err := os.Open(infile)
	if err != nil {
		return nil, fmt.Errorf("打开文件失败: %v", err)
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			fmt.Printf("文件关闭失败: %v\n\n", err)
		}
	}(file)

	fmt.Println("文件已打开，准备读取...")
	values = make([]int, 0)
	//创建一个带缓冲的 Reader
	br := bufio.NewReader(file)
	//循环读取文件中的每一行
	for {
		line, err := br.ReadString('\n')
		if err != nil {
			break
		}
		//去除字符串前后的所有空白字符
		line = strings.TrimSpace(line)
		if line == "" {
			continue  // 跳过空行
		}
		value, err := strconv.Atoi(line)
		if err != nil {
			return nil, fmt.Errorf("文件内容转换成数字失败: %v", err)
		}
		values = append(values, value)
	}
	return values, nil
}

func writeValues(outfile string, values []int) (err error) {
	file, err := os.Create(outfile)
	if err != nil {
		return fmt.Errorf("创建文件失败: %v", err)
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			fmt.Printf("文件关闭失败: %v\n\n", err)
		}
	}(file)

	fmt.Println("文件已创建，准备写入...")
	for _, value := range values {
		_, err := fmt.Fprintln(file, value)
		if err != nil {
			return fmt.Errorf("写入文件失败: %v", err)
		}
	}
	return nil
}

func main() {
	flag.Parse()
	if infile != nil {
		fmt.Println("infile:", *infile, "outfile =", *outfile, "algorithm =", *algorithm)
	}
	values, err := readValues(*infile)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Printf("readValues: %v\n", values)

	sorter.BubbleSort(values)
	fmt.Printf("BubbleSort: %v\n", values)

	sorter.ShuffleSlice( values)
	fmt.Printf("ShuffleSlice: %v\n", values)
	sorter.BubbleSortGeneric( values, func(a, b int) bool {return a < b})
	fmt.Printf("BubbleSortGeneric: %v\n", values)

	sorter.ShuffleSlice( values)
	fmt.Printf("ShuffleSlice: %v\n", values)
	values = sorter.QuickSort( values)
	fmt.Printf("QuickSort: %v\n", values)

	sorter.ShuffleSlice( values)
	fmt.Printf("ShuffleSlice: %v\n", values)
	sorter.QuickSortGeneric( values, func(a, b int) bool {return a > b})
	fmt.Printf("QuickSortGeneric: %v\n", values)
	err = writeValues(*outfile, values)
}
